<template>
  <!-- 修改模板，使用v-for来循环渲染每个图片 -->
  <div ref="container" class="waterfall-container">
    <div v-for="(column, columnIndex) in columns" :key="columnIndex" class="waterfall-column">
      <a-card hoverable v-for="(item) in column" :key="item.id">
        <template #extra v-if="isShow">
          <a-checkbox :value="item.src" @change="versionUpdate"></a-checkbox>
        </template>
        <div class="waterfall-item" :style="{
          height: `${item.height}px`,
          backgroundImage: `url('${item.src}')`,
          backgroundSize: 'cover',
        }" @click="handleTagOnline(item.id)">
        </div>
      </a-card>
    </div>
  </div>
</template>

<script>
export default {
  name: 'WaterfallFlow',
  props: ['dataList', 'isShow'],
  data() {
    return {
      items: [],
      columns: [],
      resizeObserver: null
    };
  },
  watch: {
    dataList: {
      handler() {
        this.generateItems();
      },
      immediate: true
    }
  },
  mounted() {
    this.setupResizeObserver();
  },
  beforeDestroy() {
    this.cleanupResizeObserver();
  },
  methods: {
    generateItems() {
      this.items = this.$props.dataList.map((url, index) => ({
        id: index,
        height: Math.floor(Math.random() * 200) + 100, // 这里假设所有图片高度相同，实际情况可能需要根据图片实际高度来设置
        src: url, // 图片的URL
      }));
      this.distributeItems();
    },
    setupResizeObserver() {
      this.resizeObserver = new ResizeObserver(entries => {
        for (let entry of entries) {
          const width = entry.contentRect.width;
          const columnCount = Math.floor(width / 250);
          this.distributeItems(columnCount);
        }
      });
      this.resizeObserver.observe(this.$refs.container);
    },
    cleanupResizeObserver() {
      if (this.resizeObserver) {
        this.resizeObserver.disconnect();
      }
    },
    distributeItems(columnCount = 3) {
      const newColumns = Array.from({ length: columnCount }, () => []);
      this.items.forEach((item, index) => {
        const columnIndex = index % columnCount;
        newColumns[columnIndex].push(item);
      });
      this.columns = newColumns;
    },
    handleTagOnline(id) {
      this.$emit('handleTagOnline', id);
    },
    versionUpdate() {
      this.$emit('versionUpdate')
    }
  }
};
</script>

<style scoped>
.waterfall-container {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 10px;
}

.waterfall-column {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.waterfall-item {
  width: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style>